package com.crm.service.impl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.UUID;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.crm.dao.FinanceApplyMapper;
import com.crm.dao.FinanceApproveMapper;
import com.crm.model.FinanceApply;
import com.crm.model.FinanceApprove;
import com.crm.model.SysUser;
import com.crm.service.FinanceAccraditationService;
import com.crm.util.SessionModel;
import com.crm.util.SessionUtils;
import com.mchange.lang.StringUtils;

@Service
public class FinanceAccraditationServiceImpl extends BaseServiceImpl<FinanceApprove> implements FinanceAccraditationService {
	@Autowired
	private FinanceApplyMapper applyMapper;
	@Autowired
	private FinanceApproveMapper approveMapper;
	@Override
	@Transactional(rollbackOn = { Exception.class }) 
	public int insert(FinanceApprove record) {
		int count=0;
		//审批方式默认为1
		record.setApproveWay(new Byte("1"));
		String[] applyIdArr = record.getApplyId().split(",");
		List<FinanceApply> applyList = new ArrayList<>();
		for(String applyId:applyIdArr){
			FinanceApply apply = applyMapper.selectByPrimaryKey(applyId);
			boolean flag = setNextDutyId(record.getApproveStatus(),apply);
			if(!flag) return 0; else applyList.add(apply);
		}
		SysUser sysUser =((SysUser)SessionUtils.get(SessionModel.SESSION_USER));
		for(int i=0;i<applyIdArr.length;i++){
			FinanceApply apply =applyList.get(i);
			apply.setModifyUserId(sysUser.getUserId());
			apply.setModifyDate(new Date());
			apply.setModifyUserName(sysUser.getRealName());
			record.setApproveId(UUID.randomUUID().toString());
			record.setApplyId(applyIdArr[i]);
			record.setDeleteMark(1);
			record.setEnable(1);
			applyMapper.updateByPrimaryKey(apply);
			count=super.insert(record);
		}
		return count;
	}
	@Override
	public List<FinanceApprove> getApproveFlowByApplyId(String applyId) {
		List<FinanceApprove> approveList =approveMapper.getApproveFlowByApplyId(applyId);
		return approveList;
	}

	private boolean setNextDutyId(int status, FinanceApply apply) {
		boolean flag = false;
		String currentDutyId = apply.getApproveNextDuty();
		if(apply.getDutyIdVal()==null||apply.getDutyIdVal().trim()=="") return flag;
		String[] dutyIdArr =apply.getDutyIdVal().split(",");
		for(int i=0;i<dutyIdArr.length;i++){
			if(dutyIdArr[i].equals(currentDutyId)){
				if(status==0){//审批不通过
					apply.setApplicantStatus(new Byte("2"));
					apply.setApproveNextDuty(i==0?null:dutyIdArr[i-1]);
				}else{//审批通过
					if(i==dutyIdArr.length-1)apply.setApplicantStatus(new Byte("1"));
					apply.setApproveNextDuty(i==dutyIdArr.length-1?null:dutyIdArr[i+1]);
				}
				flag = true;
				break;
			}
		}
		return flag;
	}
	

}
